#pragma once 
#include "Log.hpp"
#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>

using namespace std;
const string defaultpath = "./Dict.txt";
const string sep = ": ";

namespace yss
{
    class Dict
    {
    private:
        bool Load()
        {
            ifstream in(_filepath);
            if(!in.is_open())
            {
                LOG(FATAL, "open %s is error\n", _filepath.c_str());
                return false;
            }
            string line;
            while(getline(in, line))
            {
                if(line.empty()) continue;
                auto pos = line.find(sep);
                if(pos == string::npos) continue;
                string word = line.substr(0, pos);
                if(word.empty()) continue;
                string han = line.substr(pos+sep.size());
                if(han.empty()) continue;
                LOG(DEBUG, "load info, %s: %s\n", word.c_str(), han.c_str());

                _dict.insert(make_pair(word, han));
            }
            in.close();
            LOG(DEBUG, "load %s success\n", _filepath.c_str());
            return true;
        }
    public:
        Dict(const string& path = defaultpath)
            :_filepath(path)
        {
            Load();
        }
        string Translate(const string& word, bool &ok)
        {
            ok = true;
            auto iter = _dict.find(word);
            if(iter == _dict.end())
            {
                ok = false;
                return "未找到";
            }
            return iter->second;
        }
        ~Dict()
        {}

    private:
        unordered_map<string, string> _dict;
        string _filepath;
    };
}